package com.book.bookmanager.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.book.bookmanager.pojo.Role;
import com.book.bookmanager.service.roleService;
import com.book.common.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("role")
@Api(tags = "角色管理")
public class roleController {
    @Autowired
    private roleService rs;

    @GetMapping("all")
    @ApiOperation("列表")
    public Result<Map<String, Object>> getList() {
        Map<String, Object> data = new HashMap<>();
        data.put("id", rs.queryAll());
        return Result.success(data);
    }

    @GetMapping("queryBy")
    @ApiOperation("测试")
    public Result<Map<String, Object>> queryBy() {
        Map<String, Object> data = new HashMap<>();
        data.put("id", rs.queryAll());
        return Result.success(data);
    }
    @GetMapping("roleList")
    @ApiOperation("获取列表")
    public Result<Map<String, Object>> getRoleList(@RequestParam(value = "roleName", required = false) String roleName,
                                                   @RequestParam(value = "pageNo") Long pageNo,
                                                   @RequestParam(value = "pageSize") Long pageSize) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(roleName), Role::getRole_name, roleName);
        wrapper.orderByAsc(Role::getRole_name);
        Page<Role> page = new Page<>(pageNo, pageSize);
        rs.page(page, wrapper);

        Map<String, Object> data = new HashMap<>();
        data.put("total", page.getTotal());
        data.put("rows", page.getRecords());

        return Result.success(data);
    }

    @PostMapping("addRole")
    public Result<?> addRole(@RequestBody Role role) {
        rs.addRole(role);
        return Result.success("新增角色成功");
    }

    @PutMapping("/updateRole")
    public Result<?> updateRole(@RequestBody Role Role) {

        rs.updateRole(Role);

        return Result.success("修改角色成功");
    }

    @GetMapping("/queryByRoleId/{role_id}")
    public Result<?> queryByRoleId(@PathVariable("role_id") Integer role_id) {
        Role Role = rs.queryByRoleId(role_id);
        if (Role != null) {
            return Result.success(Role);
        }
        return Result.fail("获取角色失败，角色不存在");
    }

    @DeleteMapping("/deleteById/{role_id}")
    public Result<?> deleteById(@PathVariable("role_id") Integer role_id) {
        rs.removeByRoleId(role_id);
        return Result.success("删除成功");
    }
}
